package com.block.common.util;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Decoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * RSA加密
 * 【X509】
 * 【公钥加密】
 * 【私钥解密】
 * 
 * 2017年9月23日 上午11:38:33
 */
public class X509RsaUtil {
//	private static final Logger log = Logger.getLogger(X509RsaUtil.class);
	
    private static String RSAC = "RSA/ECB/PKCS1Padding";
    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

  
    //公钥加密
    public static String encryptByPublicKey(String data, String publicKey) {
    	try {
			byte[] dataBytes = data.getBytes();
			byte[] keyBytes = Base64Decoder.decode(publicKey);
			X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			Key publicK = keyFactory.generatePublic(x509KeySpec);
			// 对数据加密
			Cipher cipher = Cipher.getInstance(RSAC);
			cipher.init(Cipher.ENCRYPT_MODE, publicK);
			byte[] cache = cipher.doFinal(dataBytes);
			String result=Base64.encode(cache);
			return result;
    	} catch (InvalidKeyException e) {
//			log.error("【RSA加密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
//			log.error("【RSA加密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
//			log.error("【RSA加密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
//			log.error("【RSA加密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
//			log.error("【RSA加密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (BadPaddingException e) {
//			log.error("【RSA加密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
//			log.error("【RSA加密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		}
    	return null;
    }



    /**
     * <P>
     * 私钥解密
     * </p>
     *
     * @param encryptedData 已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String encryptedData, String privateKey) {
        try {
			byte[] keyBytes = Base64Decoder.decode(privateKey);
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
			Cipher cipher = Cipher.getInstance(RSAC);
			cipher.init(Cipher.DECRYPT_MODE, privateK);
			byte[] encryp=Base64Decoder.decode(encryptedData);
			byte[] decryptedData = cipher.doFinal(encryp);
			return new String(decryptedData,"utf-8");
		} catch (InvalidKeyException e) {
//			log.error("【RSA解密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
//			log.error("【RSA解密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
//			log.error("【RSA解密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
//			log.error("【RSA解密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
//			log.error("【RSA解密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (BadPaddingException e) {
//			log.error("【RSA解密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
//			log.error("【RSA解密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
//			log.error("【RSA解密出现异常】异常信息： " + e.getMessage());
			e.printStackTrace();
		}
        return null;
    }
    
    public static void main(String[] args) throws Exception {
//		String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC06B0Or9NW45kyfShcRFRsf7IlxbbzfrRuO4y+22zQjZsVChx7WyXcFy2Hxyd04MZSGFnXiPUYKJQS6LyKwARxLPagCWdoqEFM4d1RmfhTrbmUbCxyMIZeFC/DtdMnISU0IZ9XP6PS/L+AD6urjS8F3GUaovIz5onv0cgV4Va1/wIDAQAB";
		String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC06B0Or9NW45kyfShcRFRsf7IlxbbzfrRuO4y+22zQjZsVChx7WyXcFy2Hxyd04MZSGFnXiPUYKJQS6LyKwARxLPagCWdoqEFM4d1RmfhTrbmUbCxyMIZeFC/DtdMnISU0IZ9XP6PS/L+AD6urjS8F3GUaovIz5onv0cgV4Va1/wIDAQAB";
		String priKey="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALToHQ6v01bjmTJ9KFxEVGx/siXFtvN+tG47jL7bbNCNmxUKHHtbJdwXLYfHJ3TgxlIYWdeI9RgolBLovIrABHEs9qAJZ2ioQUzh3VGZ+FOtuZRsLHIwhl4UL8O10ychJTQhn1c/o9L8v4APq6uNLwXcZRqi8jPmie/RyBXhVrX/AgMBAAECgYEAtGxy3nz5WEUyOyqcIDl9waAxun5QEtUhenclzgvloLI6I2esNFMZlUIAhNRZQ7YR1Tq4D8BmQSvnUlyP/gm34sIcSKqzF6ODa/KDGd7w28DBVKN3501CZr/Z3jENv3aMFrHTL7fMNs36tCi4rnL1VoCfu4eDVAjfFaKv8NdsVgECQQDklGrqBrJ9wFe/H64b6iy/zTovERfPn0Q99ig5R2ANQnEe1pUrzs+UssVFoXsuMjo1AwN2ip6/A20EPsmskIaBAkEAyputaCZqNESImwpbQOndknMYbZPBccrgpRmZsGcVnvm/Z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upVq+qJ+Ln053YThIch95rG/sQEjD0TwRl88q7y2ecaAxIQ5S/o70eJbOuVKxQ6jnH1tHYe61OLY+xWeKg==";
		
		String encStr= X509RsaUtil.encryptByPublicKey("p0p2nr017zdlc9iu", publicKey);
		String decStr=X509RsaUtil.decryptByPrivateKey("aP1D9lo9aukpgmSSh%2BuSCzWxmhcMjUZZjRDFK2gPfwEOEu%2FtCmlkbQbYYjJiFAEo24O8ShNOz8wF%0AXWbC%2BKrIY3V9JCNqT9zqKQ5c8mabdvoIsCFHkT9%2BdG86cKrlwfs2CjEt1lW4xYxXpD0A%2BCozOO4C%0AOvW83OTwlLbgDH0%2F0Vg%3D%0A", priKey);
		
//		System.out.println(encStr);
		System.out.println(decStr);
	}

}
